package org.dg.iag.dao;

import java.io.ByteArrayInputStream;
import java.util.Formatter;

import org.apache.commons.io.ByteOrderMark;
import org.apache.commons.io.input.BOMInputStream;
import org.apache.log4j.Logger;
import org.dg.InitialServer;
import org.dg.iag.conf.ApplicationProperties;
import org.dg.iag.query.XQueryGet;
import org.dg.iag.util.ApplicationConstants;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Protocol;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.ClientResource;

public class PutDAO {
	
	public static Logger logger		= Logger.getLogger(PutDAO.class);
	
	public static boolean putIatiRepresentation(String feedTag, Representation r) {
		String relPath	= feedTag;
		if ( !relPath.endsWith(".xml") ) {
			relPath		= relPath + ".xml";
		}
		try {
			String url			= ApplicationConstants.APP_REST_PATH + ApplicationConstants.IATI_STORAGE_PATH + "/" + relPath;
			ClientResource cr 	= new ClientResource(InitialServer.configureContext(true), url);
			cr.setChallengeResponse(ChallengeScheme.HTTP_BASIC, ApplicationConstants.EXIST_USER, ApplicationConstants.EXIST_PASSWORD);
			cr.setProtocol(Protocol.HTTP);
			cr.setMethod(Method.PUT);
			cr.put(r, MediaType.TEXT_XML);
			cr.release();
			
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

//	public static String bytesToHexString(byte[] bytes) {  
//	    StringBuilder sb = new StringBuilder(bytes.length * 2);  
//	  
//	    Formatter formatter = new Formatter(sb);  
//	    for (byte b : bytes) {  
//	        formatter.format("%02x", b);  
//	    }  
//	  
//	    return sb.toString();  
//	} 
	
	public static boolean putIatiString(String feedTag, String text, boolean saveInTempFolder) {
		
		String iatiStoragePath		= ApplicationConstants.IATI_STORAGE_PATH_TEMP;
		if ( !saveInTempFolder ) {
			iatiStoragePath			= ApplicationConstants.IATI_STORAGE_PATH;
		}
		
		String relPath	= feedTag;
		if ( !relPath.endsWith(".xml") ) {
			relPath		= relPath + ".xml";
		}
		ClientResource cr = null;
//		System.out.println("---START PRINTING BYTES");
//		byte[] bytes	= text.getBytes();
//		for ( int i=0; i<bytes.length; i++ ) {
//			System.out.printf ("%02X",bytes[i]);
//			System.out.print( " | " );
//		}
//		System.out.println( bytesToHexString(bytes) );
//		System.out.println("---END PRINTING BYTES");
		ByteArrayInputStream in = new ByteArrayInputStream(text.getBytes());
	      BOMInputStream bomIn = new BOMInputStream(in);
	      try {
			if (bomIn.hasBOM()) {
			      // has a UTF-8 BOM
				System.out.println("Found BOM  - UTF8 !!!");
			  }
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		ByteArrayInputStream in2 = new ByteArrayInputStream(text.getBytes());
	try{	
		BOMInputStream bomIn2 = new BOMInputStream(in2, ByteOrderMark.UTF_16LE, 
				ByteOrderMark.UTF_16BE);
				if (bomIn2.hasBOM() == false) {
				    // No BOM found
					System.out.println("No BOM - ok");
				} else if (bomIn2.hasBOM(ByteOrderMark.UTF_16LE)) {
				    // has a UTF-16LE BOM
					System.out.println("Found BOM  - UTF_16LE !!!");
				} else if (bomIn2.hasBOM(ByteOrderMark.UTF_16BE)) {
				    // has a UTF-16BE BOM
					System.out.println("Found BOM  - UTF_16BE !!!");
				}
				else 
					System.out.println("Found  BOM not catched..............."); 
	} catch (Exception e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
				
		try {
			String url			= ApplicationConstants.APP_REST_PATH + iatiStoragePath + "/" + relPath;
			logger.info("Storing feed at " + url);
			 cr	= new ClientResource(InitialServer.configureContext(true), url);
			cr.setChallengeResponse(ChallengeScheme.HTTP_BASIC, ApplicationConstants.EXIST_USER, ApplicationConstants.EXIST_PASSWORD);
			cr.setProtocol(Protocol.HTTP);
			cr.setMethod(Method.PUT);
			StringRepresentation srep	= new StringRepresentation(text, MediaType.TEXT_XML);
			cr.put(srep, MediaType.TEXT_XML);
			cr.release();
			//cr.put(text );
		}
		catch (Exception e) {
			e.printStackTrace();
			System.out.println("ERROR on logging the feed ...");
			if(cr!=null)
				{
			     System.out.println("ERROR release the current cr ...");
				 cr.release();
				}
			return false;
		}
		
		return true;

	}
	public static boolean putString(String path, String text) {
		String relPath	= path;
		if ( !relPath.endsWith(".xml") ) {
			relPath		= relPath + ".xml";
		}
		try {
			String url			= ApplicationProperties.EXIST_REST + relPath;
			ClientResource cr 	= new ClientResource(InitialServer.configureContext(true), url);
			cr.setProtocol(Protocol.HTTP);
			cr.setMethod(Method.PUT);
			cr.setChallengeResponse(ChallengeScheme.HTTP_BASIC, ApplicationConstants.EXIST_USER, ApplicationConstants.EXIST_PASSWORD);
			
			StringRepresentation srep	= new StringRepresentation(text, MediaType.TEXT_XML);
			cr.put(srep, MediaType.TEXT_XML);
			cr.release();
			
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		return false;

	}
	
	public static void rename(String path, String newName)  {
		String query	= "xmldb:rename ('/db" + ApplicationConstants.APP_PATH +  path +
				"', '" + newName + "')";
		XQueryGet xqg	= new  XQueryGet("", query, null);
		GenericDAO<Object, Object> gdao		= new GenericDAO<Object, Object>(ApplicationConstants.APP_REST_PATH);
		
		String response 	= gdao.getElementsAsString(xqg);
		logger.info(response);
	}
	
	public static void remove(String path)  {
		String query	= "xmldb:remove ('/db" + ApplicationConstants.APP_PATH +  path +"')";
			
		XQueryGet xqg	= new  XQueryGet("", query, null);
		GenericDAO<Object, Object> gdao		= new GenericDAO<Object, Object>(ApplicationConstants.APP_REST_PATH);
		
		String response 	= gdao.getElementsAsString(xqg);
		logger.info(response);
	}
	
}
